<template>
  <el-container style="opacity: 0.9">
    <div class="author">
      <el-avatar v-if="token==null" icon="el-icon-user-solid" size="large">
        <!-- style="background-color: #666" -->
      </el-avatar>
      <el-avatar v-else :src="avatar" size="large"></el-avatar>
      <div>
        <div class="nkname">
          <span class="name" v-if="token==null">匿名用户</span>
          <span class="name" v-else>{{ name }} </span>
        </div>
      </div>
    </div>
    <el-form :model="messageForm" :rules="messageFormRules" ref="messageFormRef">
      <el-form-item prop="content">
        <el-input @blur="blur" :rows="5" v-model="messageForm.content" type="textarea" maxlength="100" show-word-limit
                  placeholder="请输入你的评论"></el-input>
      </el-form-item>
      <el-form-item style="text-align: right">
        <el-row>
          <el-col :span="12" style="text-align: right">
            <el-button type="primary" @click="publish">点击发表</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <el-divider v-if="messageList.length>0"><span style="color: #999;font-size: small;">最新评论</span></el-divider>
    <comment :comments="messageList" @replyConfirm="commitComment"></comment>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getMessageList" />
  </el-container>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import useUserStore from "@/store/modules/user";


import { getToken } from '@/utils/auth';
import { cmsListComment, cmsAddComment } from "@/api/cms/comment";
import comment from './comments.vue';
const messageFormRef = ref(null);
const userStore = useUserStore();

const router = useRouter();
const route = useRoute();
const messageList = ref([]);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  parentId: null,
  mainId: null,
  likeNum: null,
  content: null,
  type: null,
  blogId: route.query.id,
  userId: null,
  delFlag: null,
  createBy: null,
});

const messageForm = ref({});
const messageFormRules = ref({
  content: [{
    min: 0,
    max: 100,
    message: "评论内容不超过100字！"
  }]
});

const cursorIndexStart = ref(null);
const cursorIndexEnd = ref(null);

function reset() {
  messageForm.value = {
    id: null,
    parentId: null,
    mainId: null,
    likeNum: null,
    content: null,
    type: null,
    blogId: route.query.id,
    userId: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
}

async function publish() {
  let token = getToken();
  await messageFormRef.value.validate(async valid => {
    if (!valid) return;
    if (!messageForm.value.content) {
      ElMessage.error('评论内容不能为空！');
      return;
    }
    if (!token) {
      messageForm.value.createBy = "匿名用户";
      messageForm.value.type = '0';
    } else {
      messageForm.value.createBy = userStore.userName;
      messageForm.value.type = '0';
    }

    try {
      await cmsAddComment(messageForm.value);
      ElMessage.success('评论发表成功');
      reset();
      await getMessageList();
    } catch (error) {
      // Handle error if needed
    }
  });
}

async function commitComment(value) {
  debugger
  reset();
  messageForm.value.content = value.inputComment;
  messageForm.value.parentId = value.id;
  let token = getToken();
  await messageFormRef.value.validate(async valid => {
    if (!valid) return;
    if (!messageForm.value.content) {
      ElMessage.error('评论内容不能为空！');
      return;
    }
    if (!token) {
      messageForm.value.createBy = "匿名用户";
      messageForm.value.type = '1';
    } else {
      messageForm.value.createBy = userStore.userName;
      messageForm.value.type = '1';
    }

    try {
      await cmsAddComment(messageForm.value);
      ElMessage.success('评论发表成功');
      reset();
      await getMessageList();
    } catch (error) {
      // Handle error if needed
    }
  });
}

function getMessageList() {
  let token = getToken();
  if (token) {
    queryParams.value.createBy = userStore.userName;
  }

  cmsListComment(queryParams.value).then(response => {
    for (let i = 0; i < response.rows.length; i++) {
      let mesInfo = response.rows[i];
      if (mesInfo.avatar != null && mesInfo.avatar != "") {
        response.rows[i].avatar = process.env.VUE_APP_BASE_API + mesInfo.avatar;
      }
      if (mesInfo.children != null && mesInfo.children != "") {
        for (let j = 0; j < response.rows[i].children.length; j++) {
          let children = response.rows[i].children;
          if (children.avatar != null && children.avatar != "") {
            response.rows[i].children[j].avatar = process.env.VUE_APP_BASE_API + children.avatar;
          }
        };
      }
    };
    messageList.value = response.rows;
    total.value = response.total;
  });
}

function blur(e) {
  cursorIndexStart.value = e.srcElement.selectionStart;
  cursorIndexEnd.value = e.srcElement.selectionEnd;
}

function handleEmojiSelected(val) {
  if (cursorIndexStart.value !== null && messageForm.value.content) {
    messageForm.value.content = messageForm.value.content.substring(0, cursorIndexStart.value) + val + messageForm.value.content.substring(cursorIndexEnd.value);
  } else {
    messageForm.value.content = messageForm.value.content ? messageForm.value.content : '' + val;
  }
}


getMessageList();
reset();

</script>

<style scoped>
.el-container {
  display: block;
}

.author {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
  margin-bottom: 20px;
}

.comment {
  border-bottom: 1px dashed #ccc;
  margin: 30px 0;
  display: flex;
}

.content {
  text-align: left;
  font-size: 14px;
  flex-grow: 1;
}

.nkname {
  margin: 10px;
  max-width: 530px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.date {
  color: #999;
  margin-left: 10px;
}

.reply {
  margin-left: 10px;
}
</style>




<!--
<template>
  <el-container style="opacity: 0.9">
    <div class="author" style="height: 100%;background: pink;width: 100px;">
      <el-avatar v-if="token==null" icon="el-icon-user-solid" size="large">
        &lt;!&ndash; style="background-color: #666" &ndash;&gt;
      </el-avatar>
      <el-avatar v-else :src="avatar" size="large"></el-avatar>
      <span style="margin-left: 15px;font-size: 16px;" class="name" v-if="token==null">匿名用户</span>
      <span style="margin-left: 15px;font-size: 16px;" class="name" v-else>{{ name }} </span>
      <div>
&lt;!&ndash;        <div style="display: inline-block;background: yellow" class="nkname">&ndash;&gt;
&lt;!&ndash;       &ndash;&gt;
&lt;!&ndash;        </div>&ndash;&gt;
      </div>
    </div>

    <div style="background: greenyellow;margin-top: 100px;height: 100px;margin-bottom: 20px">
      <el-form  :model="messageForm" :rules="messageFormRules" ref="messageFormRef">
        <el-form-item prop="content">
          <el-input @blur="blur"
                    :rows="5"
                    v-model="messageForm.content"
                    type="textarea"
                    maxlength="100"
                    show-word-limit
                    placeholder="请输入你的评论"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-row>
            <el-col :span="12" style="text-align: left">
              <EmojiPicker @emojiSelected="handleEmojiSelected"/>
              &lt;!&ndash;<Emoji @output="output"></Emoji>&ndash;&gt;
            </el-col>
            <el-col :span="12" style="text-align: right">
              <el-button type="primary" @click="publish">点击发表</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

    </div>


   <div style="margin-top: 200px;margin-left: -280px;width: 100%">
     <el-divider v-if="messageList.length>0">
       <span style="color: #999;font-size: small;">最新评论</span>
     </el-divider>

      <div >
        <comment :comments="messageList" @replyConfirm="commitComment"></comment>

      </div>
     <pagination v-show="total>0"
                 :total="total"
                 :page.sync="queryParams.pageNum"
                 :limit.sync="queryParams.pageSize"
                 @pagination="getMessageList"/>
   </div>
  </el-container>
</template>

<script setup>

import {useRoute, useRouter} from 'vue-router';

import {
  getToken
} from '@/utils/auth';

import {
  cmsListComment,
  cmsAddComment,
} from "@/api/cms/comment";

/*这句删了评论加载不出来*/
import comment from './comments.vue';


import {ElMessage} from 'element-plus';



import useUserStore from "@/store/modules/user";
const userStore = useUserStore();

/*new*/

const route = useRoute();
const router = useRouter();
const picList = ref([]);
const editing = ref(false);
const messageList = ref([]);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  parentId: null,
  mainId: null,
  likeNum: null,
  content: null,
  type: null,
  blogId: route.query.id,
  userId: null,
  delFlag: null,
  createBy: null,
});
const messageForm = ref({});
const messageFormRules = ref({
  content: [{
    min: 0,
    max: 100,
    message: "评论内容不超过100字！"
  }]
});

const cursorIndexStart = ref(null);
const cursorIndexEnd = ref(null);

function reset() {
  messageForm.value = {
    id: null,
    parentId: null,
    mainId: null,
    likeNum: null,
    content: null,
    type: null,
    blogId: route.query.id,
    userId: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };

}



async function commitComment(value) {
  reset();
  messageForm.value.content = value.inputComment;
  messageForm.value.parentId = value.id;
  let token = getToken();
  await messageFormRef.value.validate(async valid => {
    if (!valid) return;
    if (messageForm.value.content == null || messageForm.value.content == '') {
      ElMessage.error('评论内容不能为空！');
      /*$modal.msgError("评论内容不能为空！");*/
      return;
    }
    if (token == null || token == '') {
      messageForm.value.createBy = "匿名用户";
      messageForm.value.type = '1';
    } else {
      messageForm.value.createBy = userStore.userName;
      messageForm.value.type = '1';
    }
    await cmsAddComment(messageForm.value);
    ElMessage.success('评论发表成功');
    /*$modal.msgSuccess("评论发表成功");*/
    reset();
    await getMessageList();
  });
}

async function getMessageList() {


  let token = getToken();
  if (token != null && token != '') {
    queryParams.value.createBy = userStore.userName;
  }
  const response = await cmsListComment(queryParams.value);
  for (let i = 0; i < response.rows.length; i++) {
    let mesInfo = response.rows[i];
    if (mesInfo.avatar != null && mesInfo.avatar != "") {
      response.rows[i].avatar = process.env.VUE_APP_BASE_API + mesInfo.avatar;
    }
    if (mesInfo.children != null && mesInfo.children != "") {
      for (let j = 0; j < response.rows[i].children.length; j++) {
        let children = response.rows[i].children;
        if (children.avatar != null && children.avatar != "") {
          response.rows[i].children[j].avatar = process.env.VUE_APP_BASE_API + children.avatar;
        }
      }
      ;
    }
  }
  messageList.value = response.rows;
  total.value = response.total;
}

function blur(e) {
  cursorIndexStart.value = e.srcElement.selectionStart; // 获取input输入框失去焦点时光标选中开始的位置
  cursorIndexEnd.value = e.srcElement.selectionEnd; // 获取input输入框失去焦点时光标选中结束的位置
}

function output(val) {
  if (cursorIndexStart.value !== null && messageForm.value.content) {
    //如果文本域获取了焦点，则在光标位置处插入对应字段内容
    messageForm.value.content = messageForm.value.content.substring(0, cursorIndexStart.value) + val + messageForm.value.content.substring(cursorIndexEnd.value);
  } else {
    // 如果文本域未获取焦点，则在字符串末尾处插入对应字段内容
    messageForm.value.content = messageForm.value.content ? messageForm.value.content : '' + val;
  }
}

function to() {
  if (route.query.commentId != null) {
    var toEl = document.getElementById(route.query.commentId);
    if (toEl != null) {
      if (toEl != null && toEl != "") {
        // toEl 为指定跳转到该位置的DOM节点
        let bridgeCms = toEl;
        let bodyTop = document.body;
        let heightCms = 0;
        // 计算该 DOM 节点到 bodyTop 顶部距离
        do {
          heightCms += bridgeCms.offsetTop;
          bridgeCms = bridgeCms.offsetParent;
        } while (bridgeCms !== bodyTop)
        // 滚动到指定位置
        window.scrollTo({
          top: heightCms,
          behavior: 'smooth'
        })
      }
    }
  }
}

function handleEmojiSelected(emoji) {
  // Append the selected emoji to the messageForm content
  messageForm.content += emoji;
}

async function publish() {
  let token = getToken();
  await messageFormRef.value.validate(async valid => {
    if (!valid) return;
    if (!messageForm.value.content) {
      ElMessage.error('评论内容不能为空！');
      return;
    }
    if (!token) {
      messageForm.value.createBy = "匿名用户";
      messageForm.value.type = '0';
    } else {
      messageForm.value.createBy = userStore.userName;
      messageForm.value.type = '0';
    }
    try {
      await cmsAddComment(messageForm.value);
      ElMessage.success('评论发表成功');
      reset();
      await getMessageList();
    } catch (error) {
    }
  });
}

getMessageList();
</script>

<style scoped>
.el-container {
  display: block;
}

.author {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
  margin-bottom: 20px;
}

.comment {
  border-bottom: 1px dashed #ccc;
  margin: 30px 0;
  display: flex;
}

.content {
  text-align: left;
  font-size: 14px;
  flex-grow: 1;
}

.nkname {
  margin: 10px;
  max-width: 530px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.date {
  color: #999;
  margin-left: 10px;
}

.reply {
  margin-left: 10px;
}
</style>
-->
